/*
 * @Author: lll 1280388921@qq.com
 * @Date: 2025-05-08 22:19:10
 * @LastEditors: lll 1280388921@qq.com
 * @LastEditTime: 2025-05-11 00:58:33
 * @FilePath: /lesson39/2.blockqueue/main.cc
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include <iostream>
#include "blockqueue.hpp"
#include <unistd.h>
#include "Task.hpp"
#include <ctime>

using namespace std;

string oper = "+-*/%";

void *Consumer(void *args)
{
    blockqueue<Task> *bq = static_cast<blockqueue<Task> *>(args);

    while (1)
    {
        Task data = bq->pop();
        // data.Run();
        // 计算
        // data.Run();
        data();
        cout << "处理了一个任务 , 运算结果为: " << data.Getret() << " ,thread id: " << pthread_self() << endl;
        // sleep(1);
    }
}

void *Productor(void *args)
{
    int len = oper.size();
    blockqueue<Task> *bq = static_cast<blockqueue<Task> *>(args);
    // int x=0,y=0;
    // Task data(x,y);
    while (1)
    {
        // 模拟生产者生产数据
        int x = rand() % 10 + 1; //[1,10]
        int y = rand() % 10;     //[0,9];
        char op = oper[rand() % len];
        Task data(x, y, op);
        usleep(10);

        // 计算
        bq->push(data);
        cout << "生产了一个任务: " << data.GetTask() << " ,thread id: " << pthread_self() << endl;
        sleep(1);
    }
}

int main()
{
    srand(time(nullptr));
    blockqueue<Task> *bq = new blockqueue<Task>();
    pthread_t c[3], p[5];
    for (int i = 0; i < 3; i++)
    {
        pthread_create(c + i, nullptr, Consumer, bq);
    }
    for (int i = 0; i < 5; i++)
    {
        pthread_create(p + i, nullptr, Productor, bq);
    }
    
    for (int i = 0; i < 3; i++)
    {
        pthread_join(c[i], nullptr);
    }
    for (int i = 0; i < 5; i++)
    {
        pthread_join(p[i], nullptr);
    }
    delete bq;

    return 0;
}